const UserApi = require('../../../api/user.js');
const CommonApi = require('../../../api/common.js');
const regExpUtil = require('../../utils/regExp.js');
const commonUtil = require('../../../utils/common.js');

Page({
  data: {
    loginType: 'psw',
    tickTip: '获取验证码',
    formModel: {
      username: null,
      password: null,
      loginFrom: 'xcx'
    },
    phoneModel: {
      phoneNumber: null,
      captcha: null,
      code: null,
      codeId: null,
      loginFrom: 'xcx'
    },
    isPswAgree: false,
    isAgree: false,
    timers: 60,
    countDown: null,
    phoneNumber: null,
    redirect_uri: '/pages/index/index',
    redirect_uri_type: 'tab',
    isWeiXinLogin: false,
  },

  onLoad(options) {
    if (options.redirect_uri) {
      if (options.newsTitle && options.newsId) {
        let redirectUri = options.redirect_uri + '?newsTitle='+options.newsTitle+'&newsId='+options.newsId
        this.setData({redirect_uri: redirectUri})
      } else if (options.quoteDate && options.quoteId) {
        let redirectUri = options.redirect_uri + '?quoteDate='+options.quoteDate+'&quoteId='+options.quoteId
        this.setData({redirect_uri: redirectUri})
      } else {
        this.setData({redirect_uri: options.redirect_uri})
      }
    }
    if (options.redirect_uri_type) {
      this.setData({redirect_uri_type: options.redirect_uri_type})
    }
  },

  onReady() {},
  onShow() {},
  onHide() {},
  toggleType(e){
    var type = e.currentTarget.dataset.type;
    this.setData({loginType: type})
  },
  toRegister(){
    wx.redirectTo({
      url: '/packageA/pages/register/index?redirect_uri='+this.data.redirect_uri+'&redirect_uri_type='+this.data.redirect_uri_type,
    })
  },
  forgetPsw(){
    let _phoneNumber = this.data.loginType == 'psw' ? this.data.formModel.username : this.data.phoneModel.phoneNumber;
    wx.setStorageSync('resetInfo', {'action': 'reset', phoneNumber: _phoneNumber})
    wx.redirectTo({
      url: '/packageA/pages/forgetPsw/index?redirect_uri='+this.data.redirect_uri+'&redirect_uri_type='+this.data.redirect_uri_type,
    })
  },
  startInterval(){
    let that = this;
    let countDownNum = that.data.timers;

    that.data.countDown = setInterval(()=>{
      if (countDownNum < 1) {
        that.setData({tickTip: '获取验证码', timers: 60});
        clearInterval(that.data.countDown);
      } else {
        countDownNum--;
        that.setData({
          timers: countDownNum,
          tickTip: countDownNum+'s后重发'
        })
      }
    }, 1000)
  },
  // 获取验证码
  getVerifyCode(){
    if (this.data.tickTip != '获取验证码') return;
    if (!this.data.phoneModel.phoneNumber) {
      wx.showToast({icon: 'none', title: '请输入手机号码'})
    } else if (this.data.phoneModel.phoneNumber && !regExpUtil.isPhoneNumber(this.data.phoneModel.phoneNumber)) {
      wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
    } else {
      let sendSmsList = wx.getStorageSync('sendSmsList');
      if (!sendSmsList) {
        this.setData({dialogVisible: true});
      } else {
        let current = sendSmsList.find(i=>i.phoneNumber==this.data.phoneModel.phoneNumber);
        let currentIndex = sendSmsList.findIndex(i=>i.phoneNumber==this.data.phoneModel.phoneNumber);
        if (!current) {
          this.setData({dialogVisible: true});
        } else {
          let isOverDue = new Date().getTime() - current.sendXcxLoginSmsFlagTime > 0;
          if (!isOverDue) {
            if (!current.times || Number(current.times)<3) {
              this.setData({dialogVisible: true});
            } else {
              let sendXcxLoginSmsFlagHour = current.sendXcxLoginSmsFlagHour;
              if (!sendXcxLoginSmsFlagHour) {
                current.sendXcxLoginSmsFlagHour = true;
                let date = new Date();
                date.setHours(date.getHours()+1);
                current.sendXcxLoginSmsFlagTime = date.getTime();
                sendSmsList.splice(currentIndex, 1, current);
                wx.setStorageSync('sendSmsList', sendSmsList);
              }
              wx.showToast({icon: 'none', title: '获取验证码过于频繁，请1小时后再次获取'})
            }
          } else {
            sendSmsList.splice(currentIndex, 1);
            wx.setStorageSync('sendSmsList', sendSmsList)
            this.setData({dialogVisible: true});
          }
        }
      }
    }
  },
  // 获取图形验证码弹窗传递来的数据
  getCaptchaData(e){
    console.log(e);
    this.setData({
      dialogVisible: false, 
      ['phoneModel.captcha']: e.detail.captcha,
      ['phoneModel.captchaId']: e.detail.captchaId
    })
    this.getPhoneNumberRegistered()
  },
  // 关闭图形验证码弹窗
  closeModal(){
    this.setData({
      dialogVisible: false, 
    })
  },
  // 判断手机号是否注册，已注册才发送短信验证码
  getPhoneNumberRegistered(){
    CommonApi.getPhoneNumberRegistered({phoneNumber: this.data.phoneModel.phoneNumber}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (res.data) {
            this.sendXcxLoginSms();
        } else {
            wx.showToast({icon: 'none', title: '手机号码未注册'})
            return false;
        }
      }
    })
  },
  // 发送小程序登录验证码
  sendXcxLoginSms(){
    CommonApi.sendXcxLoginSms({phoneNumber: this.data.phoneModel.phoneNumber}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        let sendSmsList = wx.getStorageSync('sendSmsList');
        if (!sendSmsList) {
          let list = [];
          let date = new Date();
          date.setMinutes(date.getMinutes()+10);
          let obj = {
            phoneNumber: this.data.phoneModel.phoneNumber,
            sendXcxLoginSmsFlag: true,
            sendXcxLoginSmsFlagTime: date.getTime(),
            times: 1
          };
          list.push(obj)
          wx.setStorageSync('sendSmsList', list)
        } else {
          let current = sendSmsList.find(i=>i.phoneNumber==this.data.phoneModel.phoneNumber);
          if (!current) {
            let list = sendSmsList;
            let date = new Date();
            date.setMinutes(date.getMinutes()+10);
            let obj = {
              phoneNumber: this.data.phoneModel.phoneNumber,
              sendXcxLoginSmsFlag: true,
              sendXcxLoginSmsFlagTime: date.getTime(),
              times: 1
            };
            list.push(obj)
            wx.setStorageSync('sendSmsList', list)
          } else {
            current.times++;
            let index = sendSmsList.findIndex(i=>i.phoneNumber==this.data.phoneModel.phoneNumber);
            sendSmsList.splice(index, 1, current);
            wx.setStorageSync('sendSmsList', sendSmsList)
          }
        }
        wx.showToast({icon: 'success', title: '短信验证码发送成功'});
        this.setData({['phoneModel.codeId']: res.data})
        this.startInterval()
      }
    })
  },
  // 校验短信验证码
  checkSms(){
    let that = this;
    CommonApi.checkSms({phoneNumber: this.data.phoneModel.phoneNumber, code: this.data.phoneModel.code, codeId: this.data.phoneModel.codeId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        console.log(res);
        if (!res.data) {
          wx.showToast({icon: 'error', title: '验证码错误'});
        } else {
          if (!that.data.isAgree) {
            wx.showToast({icon: 'none', title: '请勾选阅读并接受用户协议'});
            return;
          }
          that.phoneLogin()
        }
      } else {
        wx.showToast({icon: 'error', title: '验证码错误'});
      }
    })
  },
  // 手机号登录
  phoneLogin(){
    let that = this;
    CommonApi.phoneLogin({...this.data.phoneModel, loginFrom: 'xcx'}).then(loginRes=>{
      if (loginRes.retCode == "000000" && loginRes.errCode == "000000") {
        let expires = new Date(new Date() * 1 + loginRes.data.expiresIn * 1000)
        this.setData({phoneNumber: this.data.phoneModel.phoneNumber})
        wx.setStorageSync('lastLoginInfo', {phoneNumber: this.data.phoneModel.phoneNumber});
        wx.setStorageSync('token', loginRes.data.accessToken);
        wx.setStorageSync('tokenExpire', expires) // 记录token有效期限(毫秒值)
        setTimeout(()=>{
          that.getLoginUser()
        }, 200)
      } else {
        wx.showToast({icon: 'error', title: loginRes.errMsg})
      }
    })
  },
  handleInput(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'username') {
      this.setData({['formModel.username']: value})
    } else if (target == 'password') {
      this.setData({['formModel.password']: value})
    } else if (target == 'phoneNumber') {
      this.setData({['phoneModel.phoneNumber']: value})
    } else if (target == 'code') {
      this.setData({['phoneModel.code']: value})
    }
  },
  checkboxChange(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'isPswAgree') {
      this.setData({isPswAgree: value.length > 0})
    } else if (target == 'isAgree') {
      this.setData({isAgree: value.length > 0})
    }
  },
  formSubmit(e){
    console.log(e);
    console.log('passwordLogin');
    const that = this;
    this.setData({isWeiXinLogin: false})
    if (this.data.loginType == 'psw') {
      if (!this.data.formModel.username) {
        wx.showToast({icon: 'none', title: '请输入手机号/用户名'});
      } else if (!this.data.formModel.password) {
        wx.showToast({icon: 'none', title: '请输入登录密码'});
      } else {
        if (!this.data.isPswAgree) {
          wx.showToast({icon: 'none', title: '请勾选阅读并接受用户协议'});
          return;
        }
        CommonApi.passwordLogin({...this.data.formModel, loginFrom: 'xcx'}).then(loginRes=>{
          if (loginRes.retCode == "000000" && loginRes.errCode == "000000") {
            let expires = new Date(new Date() * 1 + loginRes.data.expiresIn * 1000)
            wx.setStorageSync('lastLoginInfo', {phoneNumber: this.data.formModel.username});
            wx.setStorageSync('token', loginRes.data.accessToken);
            wx.setStorageSync('tokenExpire', expires) // 记录token有效期限(毫秒值)
            setTimeout(()=>{
              that.getLoginUser()
            }, 200)
          } else {
            wx.showToast({icon: 'error', title: loginRes.errMsg})
          }
        })
      }
    } else {
      if (!this.data.phoneModel.phoneNumber) {
        wx.showToast({icon: 'none', title: '请输入手机号码'})
      } else if (!regExpUtil.isPhoneNumber(this.data.phoneModel.phoneNumber)) {
        wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
      } else if (!this.data.phoneModel.code) {
        wx.showToast({icon: 'none', title: '请输入验证码'})
      } else if (this.data.phoneModel.code && this.data.phoneModel.code.length!=6) {
        wx.showToast({icon: 'none', title: '请输入正确的验证码'})
      } else {
        that.checkSms();
      }
    }
  },

  // 查询登录用户详情
  getLoginUser(){
    UserApi.getLoginUser().then(userRes=>{
      if (userRes.retCode == "000000" && userRes.errCode == "000000") {
        this.setData({phoneNumber: userRes.data.phoneNumber});
        wx.setStorageSync('userInfo', userRes.data)
        wx.removeStorageSync('loginInfo')
        wx.removeStorageSync('sendSmsList')
        commonUtil.getUserServiceState();

        if (!this.data.isWeiXinLogin) {
          if (this.data.loginType == 'psw') {
            if (!userRes.data.setPassword || !userRes.data.activated) {
              wx.setStorageSync('resetInfo', {'action': 'set', phoneNumber: userRes.data.phoneNumber})
              wx.redirectTo({
                url: '/packageA/pages/forgetPsw/index?redirect_uri='+this.data.redirect_uri+'&redirect_uri_type='+this.data.redirect_uri_type,
              })
            } else {
              if (this.data.redirect_uri_type == 'tab') {
                setTimeout(()=>{
                  wx.switchTab({url: this.data.redirect_uri})
                }, 200)
              } else if (this.data.redirect_uri_type == 'link') {
                setTimeout(()=>{
                  wx.redirectTo({url: this.data.redirect_uri})
                }, 200)
              }
            }
          } else {
            if (this.data.redirect_uri_type == 'tab') {
              wx.switchTab({url: this.data.redirect_uri})
            } else if (this.data.redirect_uri_type == 'link') {
              wx.redirectTo({url: this.data.redirect_uri})
            }
          }
        } else {
          if (this.data.redirect_uri_type == 'tab') {
            wx.switchTab({url: this.data.redirect_uri})
          } else if (this.data.redirect_uri_type == 'link') {
            wx.redirectTo({url: this.data.redirect_uri})
          }
        }
        wx.showToast({icon: 'success', title: '登录成功'})
      }
    })
  },
  checkProtocol() {
    wx.navigateTo({
      url: '/packageA/pages/protocol/index',
    })
  },
  getUserProfile() {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        wx.login({
          success: (loginRes) => {
            console.log(loginRes);
            that.setData({isWeiXinLogin: true});
            that.xcxLogin(loginRes.code)
          },
        })
      }
    })
  },
  xcxLogin(code){
    let that = this;
    CommonApi.xcxLogin({code: code}).then(res=>{
      console.log(res);
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (!res.data.accessToken) {
          wx.navigateTo({
            url: '/packageA/pages/bindAccount/index?registerId='+res.data.registerId+'&loginType='+that.data.loginType+'&redirect_uri_type='+that.data.redirect_uri_type+'&redirect_uri='+that.data.redirect_uri,
          })
        } else {
          let expires = new Date(new Date() * 1 + res.data.expiresIn * 1000)
          wx.setStorageSync('token', res.data.accessToken);
          wx.setStorageSync('tokenExpire', expires) // 记录token有效期限(毫秒值)
          setTimeout(()=>{
            that.getLoginUser()
          }, 200)
        }
      } else {
        wx.showToast({icon: 'error', title: res.errMsg})
      }
    })
  },
  onUnload() {

  },

  onShareAppMessage() {
    return {
      title: "登录",
      path: "/packageA/pages/login/index",
    }
  },

  onShareTimeline() {
    return {
      title: "登录",
    }
  }
})